<template>
  <el-dialog :visible.sync="isShow" class="register" width="600px" :show-close="false">
    <div slot="title" class="title">用户注册</div>
    <el-form :model="form" :rules="rules" ref="form" label-width="87px" class="form">
      <el-form-item label="头像" prop="avatar" class="avatar_up">
        <el-upload
          class="avatar-uploader"
          :action="fileUrl"
          :show-file-list="false"
          name="image"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <!-- v-model="form.avatar" -->
          <img v-if="form.avatar" :src="baseUrl+'/'+form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <!-- <el-input v-model="form.avatar"></el-input> -->
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img class="code" :src="codeUrl" @click="codeclick" alt />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button class="btn_rcode" @click="rcodeclick" v-if="flag">获取用户验证码</el-button>
            <el-button class="btn_rcode" @click="rcodeclick" disabled v-else>{{time}}秒后获取验证码</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="toregister">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getRcodeApi, registerApi } from "@/Api/register.js";
export default {
  data() {
    return {
      timeId: "",
      time: 60,
      flag: true,
      baseUrl: process.env.VUE_APP_URL,
      fileUrl: process.env.VUE_APP_URL + "/uploads",
      codeUrl: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        rcode: "",
        code: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入昵称", trigger: "change" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
                  value
                )
              ) {
                callback();
              } else {
                callback(new Error("请正确输入手机号"));
              }
            },
            trigger: "change",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入邮箱"));
              }
            },
            trigger: "change",
          },
        ],
        avatar: [{ required: true, message: "请上传图片", trigger: "change" }],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, max: 12, message: "请输入6-12位的密码", trigger: "change" },
        ],
        code: [
          { required: true, message: "请输入图形验证码", trigger: "change" },
        ],
        rcode: [{ required: true, message: "请输入验证码", trigger: "change" }],
      },
      isShow: false,
    };
  },
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
        this.flag = true;
        clearInterval(this.timeId);
        this.time = 60;
      }
    },
  },
  methods: {
    // 点击获取短信验证码
    rcodeclick() {
      let _num = 0;
      this.$refs.form.validateField(["phone", "code"], (errMessage) => {
        if (errMessage == "") {
          _num++;
        }
      });
      if (_num == 2) {
        // this.$axios({
        //   url: "/sendsms",
        //   method: "post",
        //   withCredentials: true,
        //   data: {
        //     code: this.form.code,
        //     phone: this.form.phone,
        //   },
        // })
        getRcodeApi(this.form)
          .then((res) => {
            this.flag = false;
            this.timeId = setInterval(() => {
              this.time--;
              if (this.time <= 0) {
                this.flag = true;
                clearInterval(this.timeId);
                this.time = 60;
              }
            }, 1000);
            // window.console.log(res);
            // if (res.data.code == 200) {
            this.$message.success(res.data.data.captcha + "");
            // this.form.rcode = res.data.data.captcha;
            // } else {
            //   this.$message.error(res.data.message);
            // }
          })
          .catch((err) => err);
      } else {
        this.$message.error("请输入手机号与图形码");
      }
    },
    // 点击刷新验证码刷新
    codeclick() {
      this.codeUrl =
        process.env.VUE_APP_URL +
        "/captcha?type=sendsms&sffsd" +
        Math.random() * 999;
    },
    // 头像上传成功处理
    // handleAvatarSuccess(res, file) {
    handleAvatarSuccess(res) {
      // this.form.avatar = URL.createObjectURL(file.raw);
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    // 上传前对上传文件验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    //确定按钮点击事件   调用注册接口进行注册
    toregister() {
      // 全局表单验证
      this.$refs.form.validate((result) => {
        if (result) {
          // this.$message.success("验证成功");
          // this.$axios({
          //   url: "/register",
          //   method: "post",
          //   withCredentials: true,
          //   data: {
          //     avatar: this.form.avatar,
          //     username: this.form.username,
          //     email: this.form.email,
          //     phone: this.form.phone,
          //     password: this.form.password,
          //     rcode: this.form.rcode,
          //   },
          // })
          registerApi(this.form)
            .then(() => {
              // registerApi(this.form).then(() => {
              // window.console.log(res);
              // if (res.data.code == 200) {
              this.$message.success("注册成功");
              // this.$message.success("注册成功");
              this.isShow = false;
              // } else {
              //   this.$message.error(res.data.message);
              // }
            })
            .catch((err) => err);
        } else {
          this.$message.error("验证失败");
        }
      });
    },
  },
  created() {},
};
</script>
<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    font-size: 18px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 600;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
    background: linear-gradient(to right, #02c4fa, #1395fa);
  }
  .el-dialog__header {
    padding: 0;
  }
  .dialog-footer {
    text-align: center;
  }
  .avatar_up {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .btn_rcode {
    height: 38px;
    border: 1px solid #d3d7df;
    border-radius: 4px;
  }
  .code {
    width: 100%;
    height: 40px;
  }
}
</style>
